package com.ymatou.iapi.sellerproduct.testcase;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.iapi.productitem.service.GetProductInfoByProductIdCall;
import com.ymatou.iapi.sellerproduct.parameter.CatalogLevelBean;
import com.ymatou.iapi.sellerproduct.service.AmendProductBrandAndCategoryCall;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.annotation.TestSuite;
import com.ymt.utils.tag.P1;
import com.ymttest.business.service.AssertService;
import com.ymttest.business.service.LiveCallService;
import com.ymttest.business.service.NewJavaMongoCheckService;
import com.ymttest.business.service.SellerProductCallService;
import com.ymttest.database.mongo.LiveModelWapper;
import com.ymttest.database.mongo.LiveProductInfoWapper;
import com.ymttest.database.mongo.LiveProductModelWapper;
import com.ymttest.database.mongo.ProductDetailModelWapper;
import com.ymttest.database.mongo.YmtMongoDriverFactroy;
import com.ymttest.database.sqlwapper.YmtProductBrandWapper;
import com.ymttest.database.sqlwapper.YmtProductCategoryWapper;
import com.ymttest.database.sqlwapper.YmtProductsIWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.JsonBeanHelper;
import com.ymttest.utils.YMTDateUtil;


@TestSuite
public class Ts_AmendProductBrandAndCategory{
	private static AmendProductBrandAndCategoryCall amendProductBrandAndCategoryCall;
	private static Integer sellerId = Integer.valueOf(EnvSetup.getData("productsellerid"));
	private static String sellerName = EnvSetup.getData("productsellername");
	
	
	
	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("修改分类品牌");
	}



	/**
	 * sql映射关系
	 * @return
	 * @throws Exception
	 */
	public Map<String,String> sqlMap() throws Exception {
	    try {	    	
	    	Map<String,String> sqlMap = new HashMap<String,String>();
			sqlMap.put("JsonBeanRequest->BrandName", "sBrand");
			sqlMap.put("JsonBeanRequest->BrandID", "iBrandId");
			sqlMap.put("JsonBeanRequest->ThirdCategoryID", "iThirdCategoryId");	
			return sqlMap;
	    }catch (Exception e) {  
	        e.printStackTrace();	        
	    }  
	    return null;
	}
	
	/**
	 * Mango映射关系
	 * @return
	 * @throws Exception
	 */
	public Map<String,String> mangoMap() throws Exception {
	    try {	    	
			Map<String,String> mangoMap = new HashMap<String,String>();
			mangoMap.put("JsonBeanRequest->BrandName", "Data->Product->Product->BrandName");
			mangoMap.put("JsonBeanRequest->BrandID", "Data->Product->Product->BrandId");
			mangoMap.put("JsonBeanRequest->ThirdCategoryID", "Data->Product->Product->ThirdCategoryId");
			return mangoMap;
	    }catch (Exception e) {  
	        e.printStackTrace();	        
	    }  
	    return null;
	}
	
	public Map<String,String> mangoEnMap() throws Exception {
	    try {	    	
			Map<String,String> mangoMap = new HashMap<String,String>();
			mangoMap.put("JsonBeanRequest->BrandName", "Data->Product->Product->BrandEnName");
			mangoMap.put("JsonBeanRequest->BrandID", "Data->Product->Product->BrandId");
			mangoMap.put("JsonBeanRequest->ThirdCategoryID", "Data->Product->Product->ThirdCategoryId");
			return mangoMap;
	    }catch (Exception e) {  
	        e.printStackTrace();	        
	    }  
	    return null;
	}
	
			
	
	@Before
	public void caseUp() {
		amendProductBrandAndCategoryCall=new AmendProductBrandAndCategoryCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(amendProductBrandAndCategoryCall.getOpurl());
	}
	
	
	@After
	public void caseDown() {
		Logger.end();
	}
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_AmendProductBrandAndCategory_001() {
		Logger.start(true,"修改分类品牌");
		try {
			//TODO 补全case代码
			
			//发布一个立即上架商品
			String productID1 = addNewProductNotOnSale(sellerId, sellerName);
			
			YMTDateUtil.waitTime(1);
			
			//Call
			Map<String,Object> maplist = new HashMap<String, Object>();		    
			maplist.put("ProductID", productID1);	
			maplist.put("UserID",sellerId);			
			maplist.put("ThirdCategoryID",1194);			
			maplist.put("BrandName","Aeropostale");			
			maplist.put("BrandID",10064);			
			JSONObject result = amendProductBrandAndCategoryCall.callAndGetReturnData(maplist);
			amendProductBrandAndCategoryreturncode(result);
			
			//映射SQL关系
			Map<String,String> sqlMap = sqlMap();		
			//SQL Ymt_Products Map
			YmtProductsIWapper ymtProductsIWapper = new YmtProductsIWapper();           
			List<Map> productIDsqllist = ymtProductsIWapper.selectProductByProductIdforMap(productID1);
			HashMap<String, Object> actRetMap = (HashMap<String, Object>) productIDsqllist.get(0);			
			//SQL断言
			AssertService.assertResultEqual(sqlMap, result, actRetMap);
			
			
			if (YmtMongoDriverFactroy.isOldMongoCheck()){	
				//映射Mango关系
				Map<String,String> mangoMap = mangoEnMap();
				//Mango
				JSONObject productIDMangolist=GetProductInfoByProductIdCall.GetProductInfoByProductId(productID1);
				AssertService.assertResultEqual(mangoMap, result, productIDMangolist);
			}
			
			
			//新Mongo断言
			if (YmtMongoDriverFactroy.isNewMongoCheck()){	
				
				checkNewMongoCategory(result, productID1);

			}
			
			if (YmtMongoDriverFactroy.isNewJavaMgoCheck()){
				NewJavaMongoCheckService.checkProductMgoSyncBySQL_NewJavaMgo(productID1);
			}
			
			
			
			
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_AmendProductBrandAndCategory_002() {
		Logger.start(true,"修改分类品牌(自定义中文品牌)");
		try {
			//TODO 补全case代码
			
			//发布一个立即上架商品
			String productID1 = addNewProductNotOnSale(sellerId, sellerName);
					
			YMTDateUtil.waitTime(1);
			
			//Call
			Map<String,Object> maplist = new HashMap<String, Object>();		    
			maplist.put("ProductID", productID1);	
			maplist.put("UserID",sellerId);			
			maplist.put("BrandID",0);		
			maplist.put("BrandName","测试中文品牌");		
			JSONObject result = amendProductBrandAndCategoryCall.callAndGetReturnData(maplist);
			amendProductBrandAndCategoryreturncode(result);
			
			//映射SQL关系
			Map<String,String> sqlMap = sqlMap();			
			//SQL Ymt_Products Map
			YmtProductsIWapper ymtProductsIWapper = new YmtProductsIWapper();           
			List<Map> productIDsqllist = ymtProductsIWapper.selectProductByProductIdforMap(productID1);
			HashMap<String, Object> actRetMap = (HashMap<String, Object>) productIDsqllist.get(0);			
			//SQL断言
			AssertService.assertResultEqual(sqlMap, result, actRetMap);
			
			if (YmtMongoDriverFactroy.isOldMongoCheck()){	
				//映射Mango关系
				Map<String,String> mangoMap = mangoMap();
				//Mango
				JSONObject productIDMangolist=GetProductInfoByProductIdCall.GetProductInfoByProductId(productID1);
				AssertService.assertResultEqual(mangoMap, result, productIDMangolist);
			}
			
			//新Mongo断言
			if (YmtMongoDriverFactroy.isNewMongoCheck()){	
				
				checkNewMongoCategory(result, productID1);

			}
				
			if (YmtMongoDriverFactroy.isNewJavaMgoCheck()){
				NewJavaMongoCheckService.checkProductMgoSyncBySQL_NewJavaMgo(productID1);
			}
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}	
	
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_AmendProductBrandAndCategory_003() {
		Logger.start(true,"修改分类品牌(自定义英文品牌)");
		try {
			//TODO 补全case代码
			
			//发布一个立即上架商品
			String productID1 = addNewProductNotOnSale(sellerId, sellerName);
					
			YMTDateUtil.waitTime(1);
			
			//Call
			Map<String,Object> maplist = new HashMap<String, Object>();		    
			maplist.put("ProductID", productID1);	
			maplist.put("UserID",sellerId);			
			maplist.put("BrandID",0);		
			maplist.put("BrandName","testBrandName");		
			JSONObject result = amendProductBrandAndCategoryCall.callAndGetReturnData(maplist);
			amendProductBrandAndCategoryreturncode(result);

			//映射SQL关系
			Map<String,String> sqlMap = sqlMap();			
			//SQL Ymt_Products Map
			YmtProductsIWapper ymtProductsIWapper = new YmtProductsIWapper();           
			List<Map> productIDsqllist = ymtProductsIWapper.selectProductByProductIdforMap(productID1);
			HashMap<String, Object> actRetMap = (HashMap<String, Object>) productIDsqllist.get(0);			
			//SQL断言
			AssertService.assertResultEqual(sqlMap, result, actRetMap);
			
			
			if (YmtMongoDriverFactroy.isOldMongoCheck()){
				//映射Mango关系
				Map<String,String> mangoMap = mangoMap();
				//Mango
				JSONObject productIDMangolist=GetProductInfoByProductIdCall.GetProductInfoByProductId(productID1);
				AssertService.assertResultEqual(mangoMap, result, productIDMangolist);								
			}
			
			//新Mongo断言
			if (YmtMongoDriverFactroy.isNewMongoCheck()){	
				
				checkNewMongoCategory(result, productID1);
	
			}
			
			if (YmtMongoDriverFactroy.isNewJavaMgoCheck()){
				NewJavaMongoCheckService.checkProductMgoSyncBySQL_NewJavaMgo(productID1);
			}
			
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	
	//for hot fix
	//商品加入直播后修改品类 品牌
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_AmendProductBrandAndCategory_004(){
		Logger.start(true,"商品加入直播后修改品类 品牌");
		try {
			//add new product
			String productId = addNewProductNotOnSale(sellerId, sellerName);
			
			//create live
			List<Integer> liveIds= LiveCallService.createLivesInProcessAndInFuture(sellerId, productId, 2, 1);
			
			
			//product add to live
			liveIds.forEach(liveId->{
				try {
					SellerProductCallService.addProductInLive(sellerId,liveId,productId);
				} catch (Exception e) {
					Logger.fail(e);
				}
			});
				
			YMTDateUtil.waitTime(1);
			
			int thirdCategoryId = 1194;
			int brandId = 10065;
			
			Map<String, Object> brandMap = new YmtProductBrandWapper().getProductBrandByBrandId(brandId).get(0);
			String brandEn = brandMap.get("sBrandEn").toString();
			String brandName = brandMap.get("sBrand").toString();
			
			
			Map<String,Object> maplist = new HashMap<String, Object>();		
			
			maplist.put("UserId", sellerId);
			maplist.put("ProductID", productId);
			maplist.put("BrandID", brandId);
			maplist.put("BrandName", brandEn);
			maplist.put("ThirdCategoryID", thirdCategoryId);
			
			JSONObject result = amendProductBrandAndCategoryCall.callAndGetReturnData(maplist);
			amendProductBrandAndCategoryreturncode(result);
			
			YMTDateUtil.waitTime(1);
			
			//get category leve info 
			CatalogLevelBean catalogLevelBean = SellerProductCallService.getProductCategroyByThirdCategoryId(thirdCategoryId);

			//mongo check 
			
			LiveProductInfoWapper liveProductInfoWapper = new LiveProductInfoWapper();
			LiveProductModelWapper liveProductModelWapper = new LiveProductModelWapper();
			LiveModelWapper liveModelWapper = new LiveModelWapper();
			
			for(Integer liveId : liveIds){
				
				if (YmtMongoDriverFactroy.isOldMongoCheck()){
					//liveProductInfo
					Map<String, Object> ret = liveProductInfoWapper.getliveproductByLiveId(liveId);
					
					Map<String, Object> tgtMap = new HashMap<String,Object>();
					tgtMap.put("MasterCategoryId", catalogLevelBean.getMasterCategoryId());
					tgtMap.put("MasterCategoryName", catalogLevelBean.getMasterCategoryName());
					tgtMap.put("CategoryId", catalogLevelBean.getSecondCategoryId());
					tgtMap.put("CategoryName", catalogLevelBean.getSecondCategoryName());
					tgtMap.put("ThirdCategoryId", catalogLevelBean.getThirdCategoryId());
					tgtMap.put("ThirdCategoryName", catalogLevelBean.getThirdCategoryName());
					
					
					tgtMap.put("BrandId", brandId);
					tgtMap.put("Brand", brandName);
					tgtMap.put("BrandEN", brandEn);
					
					AssertService.assertResultEqual(tgtMap, ret,"Mongo-liveProductInfo");
				}
				
				
				if (YmtMongoDriverFactroy.isNewMongoCheck()){
					Map<String, Object> ret = liveProductModelWapper.getActivityId(liveId);
					
					Map<String, Object> tgtMap = new HashMap<String,Object>();
					tgtMap.put("MasterCategoryId", catalogLevelBean.getMasterCategoryId());
					tgtMap.put("MasterCategoryName", catalogLevelBean.getMasterCategoryName());
					tgtMap.put("CategoryId", catalogLevelBean.getSecondCategoryId());
					tgtMap.put("CategoryName", catalogLevelBean.getSecondCategoryName());
					tgtMap.put("ThirdCategoryId", catalogLevelBean.getThirdCategoryId());
					tgtMap.put("ThirdCategoryName", catalogLevelBean.getThirdCategoryName());
					
					
					tgtMap.put("BrandId", brandId);
					tgtMap.put("BrandName", brandName);
					tgtMap.put("BrandEnName", brandEn);
					
					AssertService.assertResultEqual(tgtMap, ret);
					
					
					//LiveModel
					Map<String, Object> liveModelret = liveModelWapper.getActivityId(liveId);
					//LiveModel - categoryList
					JSONArray categoryList =  new JSONArray(liveModelret.get("CategoryList").toString());
					int iThirdCategoryId = categoryList.getJSONObject(0).getInt("CategoryId");
					String sThirdCategoryName = categoryList.getJSONObject(0).getString("CategoryName");
					
					Map<String, Object> lmInfotgtMap = new HashMap<String,Object>();
					
					ArrayList brand = new ArrayList<>();
					brand.add(brandEn);
					lmInfotgtMap.put("Brands", brand);
															
					AssertService.assertResultEqual(lmInfotgtMap, liveModelret,"Mongo-LiveModel - Brands");
					
					Logger.verifyEquals(iThirdCategoryId, catalogLevelBean.getThirdCategoryId(), "Mongo-LiveModel - ThirdCategoryId");
					Logger.verifyEquals(sThirdCategoryName, catalogLevelBean.getThirdCategoryName(), "Mongo-LiveModel - ThirdCategoryName");
//					Logger.verifyEquals(1, categoryList.length(), "LiveModel - categoryList 数量");;
				}
			}
				
			
			if (YmtMongoDriverFactroy.isNewJavaMgoCheck()){
				liveIds.forEach(liveId->{
					try {
						NewJavaMongoCheckService.checkLiveMgoSyncBySQL_NewJavaMgo(liveId, productId, false);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				});
			}
			
		}catch(Exception e){
			Logger.fail(e);
		}
	}
	
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_AmendProductBrandAndCategory_005() {
		Logger.start(true,"修改商品品牌从自定义品牌修改为非自定义品牌");
		try {
			//TODO 补全case代码			
			//发布一个自定义品牌商品
			JSONObject addProductBean = JsonBeanHelper.getJsonBean("com.ymatou.iapi.sellerproduct/AddNewSellerProduct/AddNewProductTpl_Tc8.json");
			Map<String, Object> updateMap = new HashMap<String, Object>();		
			updateMap.put("UserID", sellerId);
			updateMap.put("LoginID", sellerName);
			JsonBeanHelper.updateJsonBean(addProductBean, updateMap);
			
			//call&获取返回报文
			String productID1 = (String) SellerProductCallService.addNewProduct(addProductBean).getJSONObject("Data").get("ProductID");

			YMTDateUtil.waitTime(1);
			
			//Call
			Map<String,Object> maplist = new HashMap<String, Object>();		    
			maplist.put("ProductID", productID1);	
			maplist.put("UserID",sellerId);			
			maplist.put("BrandID",0);		
			maplist.put("BrandName","测试中文品牌");		
			JSONObject result = amendProductBrandAndCategoryCall.callAndGetReturnData(maplist);
			amendProductBrandAndCategoryreturncode(result);
			
			//映射SQL关系
			Map<String,String> sqlMap = sqlMap();			
			//SQL Ymt_Products Map
			YmtProductsIWapper ymtProductsIWapper = new YmtProductsIWapper();           
			List<Map> productIDsqllist = ymtProductsIWapper.selectProductByProductIdforMap(productID1);
			HashMap<String, Object> actRetMap = (HashMap<String, Object>) productIDsqllist.get(0);			
			//SQL断言
			AssertService.assertResultEqual(sqlMap, result, actRetMap);
			
			if (YmtMongoDriverFactroy.isOldMongoCheck()){	
				//映射Mango关系
				Map<String,String> mangoMap = mangoMap();
				//Mango
				JSONObject productIDMangolist=GetProductInfoByProductIdCall.GetProductInfoByProductId(productID1);
				AssertService.assertResultEqual(mangoMap, result, productIDMangolist);
			}
			
			//新Mongo断言
			if (YmtMongoDriverFactroy.isNewMongoCheck()){	
				
				checkNewMongoCategory(result, productID1);

			}
			
			if (YmtMongoDriverFactroy.isNewJavaMgoCheck()){
				NewJavaMongoCheckService.checkProductMgoSyncBySQL_NewJavaMgo(productID1);
			}
									
		} catch (Exception e) {
			Logger.fail(e);
		}
	}	
	

	
	
	
	
	
	
	
	
	
	
	
	

	
	
	/**
	 * 接口返回信息公用信息部分断言（正向Case场景）
	 * @param dataStr 传入报文信息
	 * @throws Exception 错误信息
	 */
	public void amendProductBrandAndCategoryreturncode(JSONObject dataStr) throws Exception {
	    try {
			//返回报文断言
			String code =  dataStr.getString("Code");
			Logger.verifyIsContains(200, code, "\"Code\":200");
			String bCode =  dataStr.getString("BCode");
			Logger.verifyIsContains(0, bCode, "\"BCode\":0");
			String msg =  dataStr.getString("Msg");
			Logger.verifyIsContains("", msg, "Msg操作成功");
			String trace =  dataStr.getString("Trace");
			Logger.verifyIsNull(trace, "Trace等于空");			

	    }catch (Exception e) {
	        e.printStackTrace();
	    }
	}

	
		
	/**
	 * 发布一个立即上架商品
	 * @return 商品id
	 * @throws Exception
	 */
	public String addNewProductOnSale(int sellerId, String sellerName) throws Exception {
	    try {	    	
			//发布商品
			JSONObject addNewProductOnSaleObject = SellerProductCallService.addNewProductOnSale(sellerId, sellerName, null);
			Logger.verifyEquals(addNewProductOnSaleObject.getInt("Code"), 200, "响应报文-返回码");
			//获取返回报文的ProductID值
			String productID =  addNewProductOnSaleObject.getJSONObject("Data").getString("ProductID");
			Logger.verifyNotNull(productID, "响应报文-商品ID");
			return productID;
	    }catch (Exception e) {  
	        e.printStackTrace();	        
	    }  
	    return null;
	}
	
	/**
	 * 发布一个未上架商品
	 * @return 商品id
	 * @throws Exception
	 */
	public String addNewProductNotOnSale(int sellerId, String sellerName) throws Exception {
	    try {	    	
			//发布商品
			JSONObject addNewProductOnSaleObject = SellerProductCallService.addNewProductNotOnSale(sellerId, sellerName, null);
			Logger.verifyEquals(addNewProductOnSaleObject.getInt("Code"), 200, "响应报文-返回码");
			//获取返回报文的ProductID值
			String productID =  addNewProductOnSaleObject.getJSONObject("Data").getString("ProductID");
			Logger.verifyNotNull(productID, "响应报文-商品ID");
			return productID;
	    }catch (Exception e) {  
	        e.printStackTrace();	        
	    }  
	    return null;
	}
	
	
	public String checkNewMongoCategory(JSONObject result , String productID1) throws Exception {
	    try {	    	
	    	
	    		//检查mongo数据条数&取出数据
		    	ProductDetailModelWapper productDetailModelWapper = new ProductDetailModelWapper();
		    	Logger.verifyEquals(1, productDetailModelWapper.getCountByProductId(productID1), "商品数据应该只有1条");
		    	Map<String, Object> productDetailModelMap = productDetailModelWapper.getProductId(productID1);
		    	
		    	JSONObject bean = result.getJSONObject("JsonBeanRequest");
		    	int iBrandId = bean.getInt("BrandID");
		    	String sBrandName = bean.getString("BrandName");
		    	//category data
		    	
		    	YmtProductCategoryWapper ymtProductCategoryWapper = new YmtProductCategoryWapper();
		    	
		    	int ThirdCategoryId = Integer.parseInt(bean.get("ThirdCategoryID").toString());
		    	
		    	Map<String, Object> ret = ymtProductCategoryWapper.getProductCategoryByCategoryId(ThirdCategoryId).get(0);
		    	String ThirdCategoryName = ret.get("sCategory").toString();
		    	int CategoryId = Integer.parseInt(ret.get("iMasterCategory").toString());
		    	
		    	ret = ymtProductCategoryWapper.getProductCategoryByCategoryId(CategoryId).get(0);
		    	String CategoryName = ret.get("sCategory").toString();
		    	int MasterCategoryId = Integer.parseInt(ret.get("iMasterCategory").toString());
		    	
		    	ret = ymtProductCategoryWapper.getProductCategoryByCategoryId(MasterCategoryId).get(0);
		    	String MasterCategoryName = ret.get("sCategory").toString();
		    			
		    	Map<String, Object> checkNewMongoCategory = new HashMap<String, Object>();
		    	checkNewMongoCategory.put("ThirdCategoryId", ThirdCategoryId);
		    	checkNewMongoCategory.put("ThirdCategoryName", ThirdCategoryName);
		    	checkNewMongoCategory.put("CategoryId", CategoryId);
		    	checkNewMongoCategory.put("CategoryName", CategoryName);
		    	checkNewMongoCategory.put("MasterCategoryId", MasterCategoryId);
		    	checkNewMongoCategory.put("MasterCategoryName", MasterCategoryName);
		    	checkNewMongoCategory.put("BrandId", iBrandId);
		    	
		    	if (productDetailModelMap.get("BrandName") == null || productDetailModelMap.get("BrandName").toString().equals("")) {
			    	checkNewMongoCategory.put("BrandEnName", sBrandName);
				}else{
					checkNewMongoCategory.put("BrandName", sBrandName);
				}
		    	
		    	//Mongo 新库断言	    	
		    	AssertService.assertResultEqual(checkNewMongoCategory, productDetailModelMap);
	    	
	    }catch (Exception e) {  
	        e.printStackTrace();	        
	    }  
	    return null;
	}
	

}